/*
 * Copyright © Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ygxsk.carhome.permission;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;

import java.util.List;


/**
 * Created by YanZhenjie on 2018/1/1.
 * 这个貌似是在走了授权失败之后另外再弹窗提示的授权窗口，这里点击设置之后就是进入到系统应用设置界面
 */
public final class PermissionSetting {

    private final Context mContext;

    /**
     * 保证弹窗唯一
     */
    MaterialDialog materialDialogSetting;

    public PermissionSetting(Context _context) {
        this.mContext = _context;
    }

    public void showSetting(final int flagSetting, final Activity _activity, final List<String> permissions) {

        List<String> permissionNames = Permission.transformText(_activity, permissions);

        String message = _activity.getString(R.string.message_permission_always_failed,
                TextUtils.join("\n", permissionNames));

        //LogUtils.d("itchen---showSetting--" + message);
        //=================================================================================

        if (flagSetting == ConstantApi.PERMISSION_LOCATION_BUTTON3) {//关于定位的三个按钮的弹窗

            //这里准备设置三个按钮：暂不设置，去允许，前往设置
            MaterialDialog.Builder builder = new MaterialDialog.Builder(_activity)//
                    .title("使用提示：")//
                    .content(message)//
                    .positiveText("去允许")//
                    .negativeText("手动设置")//
                    .positiveColor(ColorUtils.getColor(R.color.red_normal))//
                    .neutralText("暂不设置")//中性的设置
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            //这个冲洗回调检查权限，相当于又一个循环一遍
                            //===============================================================================
                            //这个貌似是再启动一个activity中在activity中提示的内容

                            //LogUtils.d("itchen--点击了showSetting内部授权--去允许");

                            //RxBus.getInstance().post(new RxPermissionSetting(ConstantApi.RXBUS_PERMISSION_LOCATION));

                            /*AndPermission.with(Dutils.getApp())//
                                    .runtime()//
                                    .permission(Permission.ACCESS_FINE_LOCATION,//
                                            Permission.ACCESS_COARSE_LOCATION)//
                                    .rationale(new RuntimeRationale())//
                                    .onGranted(new Action<List<String>>() {//
                                        @Override
                                        public void onAction(List<String> permissions) {
                                            //ratin
                                            //toast(R.string.successfully);
                                            LogUtils.d("itchen--showSetting内部授权--成功");


                                        }
                                    }).onDenied(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> permissions) {

                                    //弹出失败弹窗，授权失败，即再次弹窗提示
                                    //无限循环该部分。
                                    //showSetting(flagSetting,_context,permissions);
                                    LogUtils.d("itchen--showSetting内部授权--失败");
                                }
                            }).start();*/
                            //==========================================================================
                        }
                    }).onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            setPermissionLocation(_activity);

                        }
                    }).onNeutral(new MaterialDialog.SingleButtonCallback() {//暂时不设置
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ToastUtils.showLong("请在:我的-应用设置-手机系统设置-权限中手动开启该权限。");
                        }
                    })
                    .cancelable(false);

            //保证一个弹窗的内容。
            if (materialDialogSetting != null) {
                if (materialDialogSetting.isShowing()) {
                    materialDialogSetting.dismiss();
                    materialDialogSetting = null;
                }
            }

            //查看当前所在的Activity是否活着
            if (ActivityUtils.isActivityAlive(_activity)) {
                //保证唯一的这个
                materialDialogSetting = builder.show();
            }

        } else if (flagSetting == ConstantApi.PERMISSION_LOCATION_BUTTON2) {//两个按钮的定位权限的弹窗内容

            //如果不是定位权限，而是其他的权限设置
            //这里准备设置三个按钮：暂不设置，去允许，前往设置
            MaterialDialog.Builder builder = new MaterialDialog.Builder(_activity)//
                    .title("使用提示：")//
                    .content(message)//
                    .positiveText("手动设置")//
                    .negativeText("暂不设置")//
                    .positiveColor(ContextCompat.getColor(_activity, R.color.red_normal))//
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            //这个冲洗回调检查权限，相当于又一个循环一遍
                            setPermissionLocation(_activity);
                        }
                    }).onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ToastUtils.showLong("请在:我的-应用设置-手机系统设置-权限中手动开启该权限。");
                        }
                    })
                    .cancelable(false);

            if (materialDialogSetting != null) {
                if (materialDialogSetting.isShowing()) {
                    materialDialogSetting.dismiss();
                    materialDialogSetting = null;
                }
            }

            if (ActivityUtils.isActivityAlive(_activity)) {
                materialDialogSetting = builder.show();
            }

        } else {//其他的权限的弹窗跟定位无关的内容

            MaterialDialog.Builder builder = new MaterialDialog.Builder(_activity)//
                    .title("使用提示：")//
                    .content(message)//
                    .positiveText("手动设置")//
                    .negativeText("暂不设置")//
                    .positiveColor(ContextCompat.getColor(_activity, R.color.red_normal))//
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            //这个冲洗回调检查权限，相当于又一个循环一遍
                            setPermission(_activity);
                        }
                    }).onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ToastUtils.showLong("请在:我的-应用设置-手机系统设置-权限中手动开启该权限。");
                        }
                    })
                    .cancelable(false);

            if (materialDialogSetting != null) {
                if (materialDialogSetting.isShowing()) {
                    materialDialogSetting.dismiss();
                    materialDialogSetting = null;
                }
            }
            if (ActivityUtils.isActivityAlive(_activity)) {
                materialDialogSetting = builder.show();
            }

        }

        //=================================================================================
        //2018年06月05日之前的原始代码提示内容，因为这个低版本手机展示不好看，屏蔽为保持统一
        /*new AlertDialog.Builder(_context)
                .setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission(_context);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //retain这里原始代码也没有写codes
                    }
                })
                .show();*/
        //=================================================================================
        //2018年05月24日因为添加新的权限内容,因为是yanzhenjie自己的弹窗包该模块屏蔽。
        /*final SettingService settingService = AndPermission.permissionSetting(mContext);
        AlertDialog.newBuilder(mContext)
                .setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        settingService.execute();
                    }
                })
                .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        settingService.cancel();
                    }
                })
                .show();*/
    }


    /**
     * 单独的定位权限内容
     */
    private void setPermissionLocation(final Activity _activity) {

        AndPermission.with(_activity)
                .runtime()
                .setting()
                .start(ConstantApi.REQUEST_CODE_SETTING_LOCATION);

    }

    //.onComeback(new Setting.Action() {
    // @Override
    // public void onAction() {

    //LogUtils.d("itchen---用户从-setPermissionLocation--设置界面---返回来");
    //唯一有效代码
    /*RxBus.getInstance().post(new RxPermissionSetting(ConstantApi.RXBUS_PERMISSION_LOCATION));*/

    //Toast.makeText(MainActivity.this, R.string.message_setting_comeback, Toast.LENGTH_SHORT).show();
    //CommUtils.displayToastShort(_context, _context.getResources().getString(R.string.message_setting_comeback));

    //只有定位的权限才会触发重新定位的内容，这里目前测试2个按钮的弹窗内容
                        /*if (flagSetting == ConstantApi.PERMISSION_LOCATION_BUTTON2) {
                            LogUtils.d("itchen---用户从---定位----界面返回来");
                            //携带标志再次重复检查哪块的权限是否打开
                            RxBus.getInstance().post(new RxPermissionSetting(ConstantApi.RXBUS_PERMISSION_LOCATION));
                        }else{
                            LogUtils.d("itchen---用户从---设置界面---返回来");
                        }*/
    //2018年06月06日发现这个flagSetting 标识内容是无效的。记不住用户就是从点击定位过来的
    //因为并不知道用户到底有没有打开定位权限。或者其他权限，仅仅是返回来而已。
    // }
    // })

    //}

    /**
     * Set permissions.
     */
    private void setPermission(final Activity _activity) {

        AndPermission.with(_activity)
                .runtime()
                .setting()
                .start(ConstantApi.REQUEST_CODE_SETTING);//普通的其他的权限内容

    }


}